#include "settingswidget.h"
#include "settingsmanager.h"
#include "pages.h"

QMutex SettingsWidget::mutex;
SettingsWidget* SettingsWidget::instance = NULL;

SettingsWidget::SettingsWidget(QWidget *parent) : QWidget(parent)
{
    vBoxLayoutPage = new QVBoxLayout;// 当前页面最外层的纵向布局
    topButtons = new TopButtons(QString::fromStdString(Pages::pagesString[Pages::SettingsPage]));
    spacerUnderTopButtons = new QSpacerItem(0,0,QSizePolicy::Fixed,QSizePolicy::Expanding);
    labelProgramVersion = new QLabel();
    hBoxLayoutConfigFileSetting = new QHBoxLayout;
    lineEditConfigFileSetting = new QLineEdit;
    buttonConfigFileSetting = new QPushButton("set");
    labelConfigFileSetting = new QLabel("Config File:");

    // 当前界面最外层布局
    vBoxLayoutPage->setMargin(0);// 每一个layout都要设置间距为0
    vBoxLayoutPage->setSpacing(0);

    // 添加顶部按钮
    vBoxLayoutPage->addLayout(topButtons);
    vBoxLayoutPage->addSpacerItem(spacerUnderTopButtons);

    // 添加版本字符串
    QString versionString;
    versionString = QString(VERSION_MAIN) + "-" + QString(VERSION_HASH);
#ifdef __HOST_PLATFORM_WINDOWS_
    versionString += "-windows";
#elif defined __HOST_PLATFORM_LINUX_
    versionString += "-linux";
#else
    versionString += "-unknown";
#endif
#ifdef QT_NO_DEBUG
    versionString += "-release";
#else
    versionString += "-debug";
#endif
    LOGI("program version:%s", versionString.toStdString().data());
    labelProgramVersion->setText(versionString);
    labelProgramVersion->setTextInteractionFlags(Qt::TextSelectableByMouse);
    vBoxLayoutPage->addWidget(labelProgramVersion);

    // 添加配置文件的设置
    hBoxLayoutConfigFileSetting->setMargin(0);
    hBoxLayoutConfigFileSetting->setSpacing(0);
    lineEditConfigFileSetting->setText(SettingsManager::getInstance().configFileName);
    // 指定文件扩展名，文件名支持字符、数字、下划线输入
    lineEditConfigFileSetting->setValidator(new QRegExpValidator(QRegExp("\\w*\\.ini$"), this));
    hBoxLayoutConfigFileSetting->addWidget(labelConfigFileSetting);
    hBoxLayoutConfigFileSetting->addWidget(lineEditConfigFileSetting);
    hBoxLayoutConfigFileSetting->addWidget(buttonConfigFileSetting);
    connect(buttonConfigFileSetting, &QPushButton::clicked, this, &SettingsWidget::setConfigFile);
    vBoxLayoutPage->addLayout(hBoxLayoutConfigFileSetting);

    this->setLayout(vBoxLayoutPage);
}

SettingsWidget::~SettingsWidget()
{
    LOGD("here");
}

void SettingsWidget::setConfigFile()
{
    SettingsManager::getInstance().setConfigFile(lineEditConfigFileSetting->text());
}
